package com.bbzn.device.client.service.emq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.config.Constants;
import com.bbzn.device.client.dataobject.Strategy;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.StrategyService;
import com.bbzn.device.client.utils.SpringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

/**
 * @Author: wulongbo
 * @Date : 2021/4/10 9:14
 * @Version 1.0
 */
@Service
@Slf4j
public class SubscribeService {
    @Autowired
    private StrategyService strategyService;

    @Bean
    @ServiceActivator(inputChannel = Constants.MQTT_SUBSCRIBE_CHANNEL)
    public MessageHandler bridgeMessageHandler() {
        MessageHandler messageHandler = new MessageHandler() {
            @SneakyThrows
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                //执行业务
                emqHandle((String) message.getPayload());
            }
        };
        return messageHandler;
    }


    public String emqHandle(String payLoad) {

        try {
            JSONObject jsonObject = JSON.parseObject(payLoad);
            Long channelCode = jsonObject.getLong("code");
            //业务判断
            if (null == channelCode) {
                return "channerlCode不能为空";
            }

            // 2.根据code查询具体业务实现
            Strategy strategy = strategyService.findOneByChannelCode(channelCode);
            if (null == strategy) {
                return "没有查询到该渠道信息";
            }
            String strategyBeanId = strategy.getStrategyBeanId();
            if (null == strategyBeanId) {
                return "没有配置策略BeanId";
            }
            // 使用beanid从容器获取对象
            EmqStrategy emqStrategy = SpringUtils.getBean(strategyBeanId, EmqStrategy.class);
            // 执行业务

            return emqStrategy.emqAction(payLoad);
        } catch (Exception e) {
            e.printStackTrace();
            return "处理失败 : 参数信息" + e.getMessage();
        }
    }

}
